package com.demo.java.net.socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 客户端
 */
public class TestClient {
    static Socket server;

    public static void main(String[] args) throws Exception {
        //创建一个流套接字并将其连接到指定 IP 地址的指定端口号。
        server = new Socket(InetAddress.getLocalHost(), 9999);
        //in 是用于接收服务器发送信息过来的管道
        BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
        //out 是从本程序输出信息到服务器的管道
        PrintWriter out = new PrintWriter(server.getOutputStream());
        //接收终端输入的信息
        BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            System.out.println("请输入要发送的内容：");
            //读取终端信息，这里也会阻塞
            String str = wt.readLine();
            //发送到服务器
            out.println(str);
            out.flush();
            if (str.equals("end")) {
                break;
            }
            //读取服务器返回的信息并打印
            String msg_from_server = in.readLine();
            System.out.println(msg_from_server);
        }
        in.close();
        out.close();
        wt.close();
        server.close();
    }
}
